package main

import (
	"fmt"
	"html/template"
	"net/http"
	"redissession"
)

var smanage *redissession.SessionManager

func init() {
	smanage, _ = redissession.NewSessionManager(180, "106.14.39.56:6379,100,foobared,6")
}

func success(w http.ResponseWriter, r *http.Request) {
	if smanage.SessionJudge("/login", w, r) {
		fmt.Println("session或者cookie不存在！")
		return
	}
	if r.Method == "GET" {
		t, _ := template.ParseFiles("success.gtpl")
		t.Execute(w, nil)
	}
}

func login(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		if smanage.CookieIsExists(r) {
			http.Redirect(w, r, "/success", http.StatusFound)
		} else {
			t, _ := template.ParseFiles("login.gtpl")
			t.Execute(w, nil)
		}
	} else {
		a := r.FormValue("username")
		b := r.FormValue("password")
		if a == "aaa" && b == "bbb" {
			session := smanage.GetSession()
			session.Set("username", a)
			session.Set("password", b)
			err := smanage.BeginCookie(w, r, session)
			if err != nil {
				return
			}
			http.Redirect(w, r, "/success", http.StatusFound)
		}
	}
}

func main() {
	http.HandleFunc("/login", login)
	http.HandleFunc("/success", success)
	err := http.ListenAndServe(":8000", nil)
	if err != nil {
		fmt.Println(err)
	}
}
